package com.exam.examtest.util

import android.content.Context
import android.database.sqlite.SQLiteDatabase
import com.exam.examtest.MyApplication
import com.exam.examtest.bean.HttpRecordBean
import com.exam.examtest.greendao.dao.DaoMaster
import com.exam.examtest.greendao.dao.HttpRecordBeanDao

/**
 * ClassName DBHelper
 * Create by rhf
 * Create on 2021/3/31 16:16
 * Description 数据库操作工具类
 */
class DBHelper {

    private val dbName = "kc_db"
    private var openHelper: DaoMaster.DevOpenHelper? = null
    private var mContext: Context

    init {
        mContext = MyApplication.getInstance()!!
        openHelper = DaoMaster.DevOpenHelper(mContext, dbName)
    }

    companion object {
        @JvmStatic
        fun getInstance(): DBHelper {
            return DbUtilHelperHolder.INSTANCE
        }
    }

    private object DbUtilHelperHolder {
        val INSTANCE = DBHelper()
    }

    /**
     * 获取可读数据库
     */
    private fun getReadableDatabase(): SQLiteDatabase {
        if (openHelper == null) {
            openHelper = DaoMaster.DevOpenHelper(mContext, dbName)
        }
        return openHelper!!.getReadableDatabase()
    }

    /**
     * 获取可写数据库
     */
    private fun getWritableDatabase(): SQLiteDatabase {
        if (openHelper == null) {
            openHelper = DaoMaster.DevOpenHelper(mContext, dbName)
        }
        return openHelper!!.getWritableDatabase()
    }

    /**
     * 保存数据
     */
    fun saveData(httpRecordBean: HttpRecordBean) {

        val daoMaster = DaoMaster(getWritableDatabase())
        val daoSession = daoMaster.newSession() ?: return
        val recordBeanDao = daoSession.httpRecordBeanDao

        //存储数据
        recordBeanDao.insert(httpRecordBean)
    }

    /**
     * 删除数据
     * @param httpRecordBean 删除的数据
     */
    fun deleteRecordData(httpRecordBean: HttpRecordBean) {
        val daoMaster = DaoMaster(getWritableDatabase())
        val daoSession = daoMaster.newSession()
        val infoBeanDao = daoSession.httpRecordBeanDao
        infoBeanDao.delete(httpRecordBean)
    }

    /**
     * 更新数据
     *
     * @param info 数据bean
     */
    fun updateRecordData(info: HttpRecordBean) {
        val daoMaster = DaoMaster(getWritableDatabase())
        val daoSession = daoMaster.newSession()
        val beanDao = daoSession.httpRecordBeanDao
        beanDao.update(info)
    }

    /**
     * @param type 数据类型
     * @return 分类数据
     */
    fun queryRecordByType(type: Int): List<HttpRecordBean> {
        val daoMaster = DaoMaster(getReadableDatabase())
        val daoSession = daoMaster.newSession()
        val downInfoDao = daoSession.httpRecordBeanDao
        val qb = downInfoDao.queryBuilder()
        qb.where(HttpRecordBeanDao.Properties.Type.eq(type))
        qb.orderDesc(HttpRecordBeanDao.Properties.HttpTimeStamp)
        //qb.limit(20);//最多读取20条数据
        return qb.list()
    }

}